package com.uiao.stone.common.exception;

import org.apache.log4j.Logger;
import org.springframework.core.Ordered;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author uiao
 * @Title: 全局异常处理
 * @date 2018/8/6 18:16
 */
public class ExceptionHandler implements HandlerExceptionResolver, Ordered {
    Logger logger = Logger.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        logger.error("异常请求URL：" + request.getRequestURL());
        if (o instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            Method method = handlerMethod.getMethod();
            logger.warn("处理器的方法为：" + method.getName());
        }
        logger.error("异常栈 ==>> ");
        logger.error(e.getMessage());

        if (e instanceof NoHandlerFoundException) {
            responseJson(response, "请求的页面不存在");
            return new ModelAndView((String) null);
        } else if (e instanceof ServletException) {
            responseJson(response, null);
            return new ModelAndView((String) null);
        } else if (e instanceof PermissionDefineException) {
            responseJson(response, "您没有权限进行该操作");
            return new ModelAndView((String) null);
        } else if (e instanceof BaseException) { // 自定义的异常
            responseJson(response, "数据异常~ 请稍后再试");
            return new ModelAndView((String) null);
        } else { // java语言错误
            responseJson(response, "服务器异常~ 请稍后再试");
            return new ModelAndView((String) null);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private void responseJson(HttpServletResponse response, String content) {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(content);
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
